import React, { useState, useCallback, useMemo } from 'react'
import { createRootRoute, Outlet, useRouter, useLocation } from '@tanstack/react-router'
import { Layout, theme, ConfigProvider } from 'antd'
import { Result, Button } from 'antd'
import { Link as RouterLink } from '@tanstack/react-router'
// 引入新创建的组件
import AIAssistant from '../components/AIAssistant'
import AIAssistantButton from '../components/AIAssistantButton'
import BreadcrumbNav from '../components/BreadcrumbNav'
import RecentTabs from '../components/RecentTabs'
import UserHeader from '../components/UserHeader'
import Toolbar from '../components/Toolbar'
import MenuSearch from '../components/MenuSearch'
import CustomSidebar from '../components/CustomSidebar'
// 引入工具函数
import { generateBreadcrumbItems } from '../utils/breadcrumbUtils'
import { generateMenuItems } from '../utils/menuUtils'
// 引入标签页管理hook
import { useTabManager } from '../hooks/useTabManager'
// 引入主题管理hook
import { useTheme } from '../hooks/useTheme'
import type { MenuProps } from 'antd'

const { Header, Content, Footer } = Layout

// NotFound 组件
const NotFound: React.FC = () => {
  return (
    <Result
      status="404"
      title="404"
      subTitle="抱歉，您访问的页面不存在。"
      extra={
        <RouterLink to="/">
          <Button type="primary">返回首页</Button>
        </RouterLink>
      }
    />
  )
}

export const Route = createRootRoute({
  component: RootComponent,
  notFoundComponent: NotFound,  // 添加 NotFound 组件
})

function RootComponent() {
  const router = useRouter()
  const location = useLocation()
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken()

  // 使用标签页管理hook
  const { tabs, activeTab, handleTabChange, handleTabEdit } = useTabManager()

  // 使用主题管理hook
  const { theme: themeMode, setThemeMode } = useTheme()

  // 侧边栏折叠状态
  const [collapsed, setCollapsed] = useState(false)

  // AI助手状态
  const [aiVisible, setAiVisible] = useState(false)
  
  // 语言状态
  const [language, setLanguage] = useState('zh-CN')

  // 模拟当前用户信息
  const currentUser = useMemo(() => ({
    id: 1,
    name: '管理员',
    email: 'admin@example.com',
    role: 'admin',
    status: 'active' as const
  }), [])

  // 用户下拉菜单项
  const userMenuItems: MenuProps['items'] = useMemo(() => [
    {
      key: 'profile',
      label: '个人中心',
    },
    {
      key: 'settings',
      label: '设置',
    },
    {
      key: 'divider',
      type: 'divider',
    },
    {
      key: 'logout',
      label: '退出登录',
    },
  ], [])

  // 生成面包屑项
  const breadcrumbItems = useMemo(() => 
    generateBreadcrumbItems(location.pathname, router), 
    [location.pathname, router]
  )

  // 生成侧边栏菜单项
  const menuItems = useMemo(() => 
    generateMenuItems(router), 
    [router]
  )

  // 处理主题切换
  const handleThemeChange = useCallback((theme: 'light' | 'dark') => {
    setThemeMode(theme)
  }, [setThemeMode])

  // 处理语言切换
  const handleLanguageChange = useCallback((language: string) => {
    setLanguage(language)
    // 这里可以添加实际的语言切换逻辑
  }, [])

  // 处理标签页点击
  const handleTabClick = useCallback((key: string) => {
    // 使用TanStack Router的navigate函数进行路由跳转
    router.navigate({ to: key })
  }, [router])

  // 处理菜单选择
  const handleMenuSelect = useCallback((path: string) => {
    // 使用TanStack Router的navigate函数进行路由跳转
    router.navigate({ to: path })
  }, [router])

  // 处理侧边栏折叠
  const handleCollapse = useCallback((collapsed: boolean) => {
    setCollapsed(collapsed)
  }, [])

  // 生成工具栏props
  const toolbarProps = useMemo(() => ({
    theme: themeMode,
    onThemeChange: handleThemeChange,
    language,
    onLanguageChange: handleLanguageChange,
    recentTabs: tabs.map(tab => ({ key: tab.key, label: tab.label })),
    onTabClick: handleTabClick
  }), [themeMode, handleThemeChange, language, handleLanguageChange, tabs, handleTabClick])

  // 生成用户头部props
  const userHeaderProps = useMemo(() => ({
    userName: currentUser.name,
    menuItems: userMenuItems
  }), [currentUser.name, userMenuItems])

  // 生成最近标签页props
  const recentTabsProps = useMemo(() => ({
    activeKey: activeTab,
    onChange: handleTabChange,
    onEdit: handleTabEdit,
    items: tabs.map(tab => ({
      key: tab.key,
      label: tab.label,
      closable: tab.key !== '/',
      children: (
        <div
          style={{
            padding: 24,
            minHeight: 360,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <Outlet />
        </div>
      ),
    }))
  }), [activeTab, handleTabChange, handleTabEdit, tabs, colorBgContainer, borderRadiusLG])

  return (
    <ConfigProvider
      theme={{
        algorithm: themeMode === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
      }}
    >
      <Layout style={{ minHeight: '100vh' }}>
        <CustomSidebar 
          items={menuItems} 
          selectedKeys={[location.pathname]} 
          collapsed={collapsed}
          onCollapse={handleCollapse}
        />
        <Layout>
          <Header style={{ 
            padding: '0 16px', 
            background: colorBgContainer, 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'space-between' 
          }}>
            <Toolbar {...toolbarProps} />
            <UserHeader {...userHeaderProps} />
          </Header>
          <Content style={{ margin: '16px 16px 0' }}>
            <BreadcrumbNav items={breadcrumbItems} />
            <RecentTabs {...recentTabsProps} />
          </Content>
          <Footer style={{ textAlign: 'center' }}>
            Admin System ©{new Date().getFullYear()} Created by AddZero
          </Footer>
        </Layout>
        
        {/* AI助手浮动按钮 */}
        <AIAssistantButton onClick={() => setAiVisible(true)} />
        
        {/* AI助手对话框 */}
        <AIAssistant visible={aiVisible} onClose={() => setAiVisible(false)} />
      </Layout>
    </ConfigProvider>
  )
}